/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.app.brilliant.shiro.controller;

import com.app.brilliant.common.api.ApiResult;
import com.app.brilliant.common.controller.BaseController;
import com.app.brilliant.game.service.BriUserPlanService;
import com.app.brilliant.shiro.param.LoginParam;
import com.app.brilliant.shiro.param.RegisterParam;
import com.app.brilliant.shiro.service.LoginService;
import com.app.brilliant.shiro.util.JwtTokenUtil;
import com.app.brilliant.shiro.vo.dev.LoginDevUserTokenVo;
import com.app.brilliant.shiro.vo.sys.LoginSysUserTokenVo;
import com.app.brilliant.sys.service.DevUserService;
import com.app.brilliant.util.CookiesUtil;
import com.app.brilliant.util.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import com.app.brilliant.sign.constant.Constants;
/**
 * 登陆控制器
 *
 * @author geekidea
 * @date 2019-09-28
 * @since 1.3.0.RELEASE
 **/
@Slf4j
@RestController
@Api(tags = "用户登录注册")
@RequestMapping("/dev")
public class DevLoginController extends BaseController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private DevUserService devUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    @ApiOperation(value = "注册", notes = "用户注册", response = LoginSysUserTokenVo.class)
    public ApiResult register(@Valid RegisterParam registerParam) throws Exception {
        // 基础参数校验已由注解完成，这里补充邮箱格式与验证码校验
        registerParam.setUsername(registerParam.getEmail());
        String email = registerParam.getEmail();
        String emailCode = registerParam.getEmailCode();
        if (!email.matches("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")) {
            return ApiResult.fail("邮箱格式不正确");
        }
        String redisKey = String.format(Constants.NomalRedisKey.registerEmailKey, email);
        Object cached = redisTemplate.opsForValue().get(redisKey);
        if (cached == null || !emailCode.equals(cached.toString())) {
            return ApiResult.fail("邮箱验证码不正确或已过期");
        }
        // 验证码一次性，注册前删除
        redisTemplate.delete(redisKey);
        return result(devUserService.register(registerParam));
    }

    @PostMapping("/loginByEmailCode")
    @ApiOperation(value = "登陆", notes = "用户登陆", response = LoginSysUserTokenVo.class)
    public ApiResult<LoginDevUserTokenVo> login(
            @ApiParam(hidden = true) @CookieValue(value = "verifyToken", required = false) String verifyToken,
            @Valid LoginParam loginParam, HttpServletResponse response) throws Exception {
        LoginDevUserTokenVo loginDevUserTokenVo = loginService.devLogin(loginParam, verifyToken);
        // 设置token响应头
        response.setHeader(JwtTokenUtil.getTokenName(), loginDevUserTokenVo.getToken());
        CookiesUtil.setCookie(response, JwtTokenUtil.getTokenName(), loginDevUserTokenVo.getToken(), -1);
        return ApiResult.ok(loginDevUserTokenVo, "登陆成功");
    }

    @PostMapping("/logout")
    public ApiResult logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        loginService.logoutDev(request);
        CookiesUtil.setCookie(response, "token", "", 0);
        return ApiResult.ok("退出成功");
    }

    @GetMapping("/getRequestIp")
    public ApiResult getRequestIp() {
        return ApiResult.ok(IpUtil.getRequestIp());
    }


}
